import wx
import wx.lib.scrolledpanel as scrolled


class WordPanel(scrolled.ScrolledPanel):
    def __init__(self, parent, config):
        super().__init__(parent)
        self.config = config
        self.word_data = []
        self.show_all_definitions = False
        self.init_ui()

    def init_ui(self):
        self.SetBackgroundColour(wx.Colour(240, 240, 240))
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(self.sizer)
        self.SetupScrolling()

    def load_words(self, word_data, show_all_definitions=None):
        if show_all_definitions is None:
            show_all_definitions = False
        self.show_all_definitions = show_all_definitions

        # 清除现有内容
        self.sizer.Clear(True)
        self.word_data = word_data

        for idx, word_info in enumerate(word_data):
            self.add_word_row(word_info, idx)

        self.Layout()
        self.SetupScrolling()
        self.Refresh()

    def add_word_row(self, word_info, idx):
        row_sizer = wx.BoxSizer(wx.HORIZONTAL)
        row_sizer.AddSpacer(10)

        # 学习状态复选框
        status_cb = wx.CheckBox(self, label="已掌握", name=f"status_{idx}")
        status_cb.SetValue(word_info.get('status', 'unlearned') == 'learned')
        status_cb.Bind(wx.EVT_CHECKBOX, lambda e: self.on_status_change(e, idx))
        row_sizer.Add(status_cb, 0, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 10)

        # 单词和音标（始终显示）
        word_text = wx.StaticText(self, label=f"{word_info.get('word', '')} {word_info.get('phonetic', '')}")
        word_text.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD))
        row_sizer.Add(word_text, 1, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 10)

        # 词义区域（根据状态显示）
        definition_text = wx.StaticText(self, label=self.get_definition_display(word_info))
        definition_text.SetFont(wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))
        row_sizer.Add(definition_text, 2, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 10)

        # 显示/隐藏词义按钮
        show_btn = wx.Button(self, label="显示词义" if definition_text.GetLabel() == "******" else "隐藏词义",
                             name=f"show_{idx}")
        show_btn.Bind(wx.EVT_BUTTON, lambda e: self.on_show_definition(e, idx))
        row_sizer.Add(show_btn, 0, wx.ALIGN_CENTER_VERTICAL)

        row_sizer.AddSpacer(10)
        self.sizer.Add(row_sizer, 0, wx.EXPAND | wx.ALL, 5)

        # 分隔线
        self.sizer.Add(wx.StaticLine(self), 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 10)

    def get_definition_display(self, word_info):
        if self.show_all_definitions:
            return word_info.get('definition', '') if self.show_all_definitions else "******"
        else:
            return "******"

    def on_status_change(self, event, idx):
        checked = event.IsChecked()
        status = 'learned' if checked else 'unlearned'
        self.word_data[idx]['status'] = status
        event.Skip()  # 让事件继续传播

    def on_show_definition(self, event, idx):
        # 找到对应的StaticText控件
        row_sizer = self.sizer.GetItem(idx * 2).GetSizer()
        for item in row_sizer.GetChildren():
            window = item.GetWindow()
            if isinstance(window, wx.StaticText) and not isinstance(window, wx.CheckBox):
                # 修改这里：点击时切换显示状态
                if window.GetLabel() == "******":
                    window.SetLabel(self.word_data[idx].get('definition', ''))
                else:
                    window.SetLabel("******")
                break
        self.Layout()

    def update_display_mode(self, show_all):
        self.show_all_definitions = show_all
        for idx, word_info in enumerate(self.word_data):
            row_sizer = self.sizer.GetItem(idx * 2).GetSizer()
            for item in row_sizer.GetChildren():
                if isinstance(item.GetWindow(), wx.StaticText) and not isinstance(item.GetWindow(), wx.CheckBox):
                    text_ctrl = item.GetWindow()
                    # 只更新当前显示词义的控件
                    if text_ctrl.GetLabel() in ["******", word_info.get('definition', '')]:
                        text_ctrl.SetLabel(self.get_definition_display(word_info))
                        break
        self.Layout()